local UIDebrisLevelUp   = UIBase.New(PanelResNames.UIDebrisLevelUp)
local fragMgr           = StrangeFragmentManager

local this = UIDebrisLevelUp

local m_chip_info = nil
local m_cur_list  = nil

local m_exp_list  = nil
local m_selected_list = {}

function UIDebrisLevelUp.Init(data)
    m_chip_info = data

    UIBase.Init(UIDebrisLevelUp)
end

local sort_func = function(a,b)
    if a.quality ~= b.quality then
        return a.quality < b.quality
    else
        if a.level ~= b.level then
            return a.level < b.level
        end
    end
    return tonumber(a.itemModelId) > tonumber(b.itemModelId)
end

function UIDebrisLevelUp:OnCreate(  )
    self:RegisterOnClick(self:GetChild("btnBack"), self.OnClick_close)
    self:RegisterOnClick(self:GetChild("btnLevelUp"), self.OnClick_levelup)
    self:RegisterOnClick(self:GetChild("btnQuickChoose"), self.OnClick_quickChoose)
    self:RegisterOnClick(self:GetChild("bgClose"), self.OnClick_close)

    this.btn_levelup    = self:GetChild("btnLevelUp")
    this.inlayItem      = self:GetChild("Item")
    this.txt_name       = self:GetChild("name")
    this.txt_skill      = self:GetChild("skill")
    this.scroll_list    = self:GetChild("list")
    this.ctr_nothing    = self:GetController("nothing")
    this.txt_level1     = self:GetChild("level/num1")
    this.txt_level2     = self:GetChild("level/preNum1")
    this.txt_power1     = self:GetChild("power/num1")
    this.txt_power2     = self:GetChild("power/preNum1")
    this.slider         = self:GetChild("Slider")
    this.txt_sliderNum  = self:GetChild("sliderNum")
    this.txt_skilldes   = self:GetChild("skill/textSkillType")
    this.ctr_levelUp    = self:GetController("ifLevelUp")
    this.txt_skilldes2  = self:GetChild("skill2/textSkillType")
    this.ctr_level      = self:GetChild("level"):GetController("ifLevelUp")
    this.ctr_power      = self:GetChild("power"):GetController("ifLevelUp")
    this.ctr_attr       = self:GetController("attr")
    this.effect         = self:GetChild("effect_zbjl").wrapTarget


    this.ctr_attr.selectedIndex = 1

    this.listAttr       = self:GetChild("listAttr")

    this.listAttr.itemRenderer = this.ArrRender

    this.txt_name.text = m_chip_info.name
    this.txt_level1.text = m_chip_info.level
    this.txt_power1.text = getNumString(m_chip_info.addPower)

    m_cur_list = this.GetStuffList()

    this.txt_skilldes.text = m_chip_info.GetMainSkillDes()
    UIDebrisLevelUp.RefreshArr()
end

function UIDebrisLevelUp.AddEvent()
    ListenEvent(Config.EventType.Debris_Upgrade, this.OnUpgradeLevel)
end

function UIDebrisLevelUp.RemoveEvent()
    CloseEvent(Config.EventType.Debris_Upgrade, this.OnUpgradeLevel)
end

function UIDebrisLevelUp.OnUpgradeLevel()
    AudioManager.Play(2015)
    -- UISysTips.AddMsg(getLanguage("升级成功"))
    UIDebrisLevelUp.Refresh()
    UIDebrisLevelUp.RefreshArr()
    Util.PlayAction(this.effect, "idle", false)
end

local m_attr_list
function UIDebrisLevelUp.RefreshArr(config)
    m_attr_list = {}
    local left = m_chip_info.GetAttr()
    if config then
        local right = decodeJsonStrToTabel(config.f_DebrisBasic)

        for k,v in pairs(left) do
            table.insert(m_attr_list, {left = v, right = right[k]})
        end
    else
        for k,v in pairs(left) do
            table.insert(m_attr_list, {left = v})
        end
    end

    this.listAttr.numItems = table.getn(m_attr_list)
end

function UIDebrisLevelUp.ArrRender(index, obj)
    local ctr_up = obj:GetController("ifLevelUp")
    local txt_name = obj:GetChild("title")
    local txt_old = obj:GetChild("num1")
    local txt_new = obj:GetChild("preNum1")

    local attr = m_attr_list[index + 1]
    if attr.right then
        ctr_up.selectedIndex = 0
        local at = G.dataTable["t_attributelibrary"][tostring(attr.left[1])]
        if at then
            local type = at.f_AttributeType
            txt_name.text = at.f_AttributeName
            if type == 2 then
                txt_old.text = "+" .. attr.left[2] * 0.01 .. "%"
                txt_new.text = "+" ..  attr.right[2] * 0.01 .. "%"
            else
                txt_old.text = "+" .. attr.left[2]
                txt_new.text = "+" ..  attr.right[2]
            end
        end
        --txt_new.text = attr
    else
        ctr_up.selectedIndex = 1
        local at = G.dataTable["t_attributelibrary"][tostring(attr.left[1])]
        if at then
            local type = at.f_AttributeType
            txt_name.text = at.f_AttributeName
            if type == 2 then
                txt_old.text = "+" .. attr.left[2] * 0.01 .. "%"
            else
                txt_old.text = "+" .. attr.left[2]
            end
        end
    end
end

--初始化物品信息
function UIDebrisLevelUp.SetData(index,obj)
    local item = CtrlManager.GetCtrl(PanelNames.Item)
    obj:GetController("select").selectedIndex = 1
    local ctr_select = obj:GetController("choose")
    local txt_num = obj:GetChild("num")
    if item ~= nil then
        local chip = m_cur_list[index + 1]
        if chip.itemType == EnumConst.ItemTypeEnum.Fragment then
            StrangeFragmentManager.SetItemData(obj, chip, true)
        else
            item.initData(obj, chip, 1, false)
        end
        -- item.initData(obj, chip, 1, false)


        if m_selected_list[chip.itemId] then
            ctr_select.selectedIndex = 1
            if chip.Num then
                txt_num.text = table.concat({getNumString(chip.Num) , "/", getNumString(chip.num) })
            else
                txt_num.text = ""
            end
        else
            ctr_select.selectedIndex = 0
        end

        obj.onClick:Clear()
        obj.onClick:Add(function()
            this.OnSelectItem(chip, obj)
        end)
    end
end

function UIDebrisLevelUp.OnSelectItem(chip, obj)
    local ctr_select = obj:GetController("choose")
    local txt_num = obj:GetChild("num")

    local need = this.GetUpgradeNeedExp(m_chip_info)
    if need == 0 then
        UISysTips.AddMsg(getLanguage("DebrisText24"))
        return
    end

    if chip.lock == 1 then
        UISysTips.AddMsg(getLanguage("DebrisText26"))
        return
    end

    local select_exp = m_chip_info.exp

    if m_selected_list[chip.itemId] then
        if chip.itemType == EnumConst.ItemTypeEnum.Fragment then
            m_selected_list[chip.itemId] = nil
            ctr_select.selectedIndex = 0
        else

            local num = m_selected_list[chip.itemId].Num
            if num > 1 then
                m_selected_list[chip.itemId].Num = num - 1
                txt_num.text = table.concat({getNumString(m_selected_list[chip.itemId].Num) , "/", getNumString(m_selected_list[chip.itemId].num) })
            else
                m_selected_list[chip.itemId] = nil
                txt_num.text = ""
                ctr_select.selectedIndex = 0
            end
        end
    else
        if chip.itemType == EnumConst.ItemTypeEnum.Fragment then
            m_selected_list[chip.itemId] = chip
            ctr_select.selectedIndex = 1
        else
            local count = math.ceil((need - select_exp)/ chip.itemFunction[2])
            if count > chip.num then
                chip.Num = chip.num
            else
                chip.Num = count
            end
            ctr_select.selectedIndex = 1
            m_selected_list[chip.itemId] = chip

            txt_num.text = table.concat({getNumString(m_selected_list[chip.itemId].Num) , "/", getNumString(m_selected_list[chip.itemId].num) })
        end
    end

    local sk_config = nil
    for _,v in pairs(m_selected_list) do
        if v.itemType == EnumConst.ItemTypeEnum.Fragment then
            sk_config = dataTable.getDataTableByStringId("t_debrismajorskill",v.f_SkillId + v.level)
            if sk_config then
                select_exp = select_exp + sk_config.f_Exp
            end
        else
            if v.itemFunction then
                select_exp = select_exp + v.Num * v.itemFunction[2]
            end
        end
    end
    UIDebrisLevelUp:OnSelectExpChanged(select_exp)
end

function UIDebrisLevelUp:OnSelectExpChanged(selectExp)
    local need = this.GetUpgradeNeedExp(m_chip_info)
    if need == 0 then
        UISysTips.AddMsg(getLanguage("DebrisText24"))
    else
        local sk_config = nil
        if selectExp >= need then
            local nextlv = m_chip_info.level + 1
            sk_config = dataTable.getDataTableByStringId("t_debrismajorskill",m_chip_info.f_SkillId + nextlv)
            if sk_config then
                local count = 100
                while sk_config and selectExp >= sk_config.f_TotalExp do
                    sk_config =  dataTable.getDataTableByStringId("t_debrismajorskill",m_chip_info.f_SkillId + nextlv + 1)
                    if sk_config then
                        if selectExp >= sk_config.f_TotalExp then
                            nextlv = nextlv + 1
                        end
                    else
                        break
                    end

                    count = count - 1
                    if count < 0 then
                        break
                    end
                end

                this.ctr_levelUp.selectedIndex = 1

                sk_config =  dataTable.getDataTableByStringId("t_debrismajorskill",m_chip_info.f_SkillId + nextlv)
                if sk_config then
                    this.txt_skilldes2.text = getLanguage(sk_config.f_DebrisLevelDesc)
                    this.RefreshArr(sk_config)
                end

                this.ctr_level.selectedIndex = 0
                this.ctr_power.selectedIndex = 0
                this.txt_level2.text = nextlv
                this.txt_power2.text = getNumString(sk_config.f_DebrisLevelPower)
            else
                this.ctr_levelUp.selectedIndex = 0
                UIDebrisLevelUp.RefreshArr()
                this.ctr_level.selectedIndex = 1
                this.ctr_power.selectedIndex = 1
            end
        else
            UIDebrisLevelUp.RefreshArr()
            this.ctr_levelUp.selectedIndex = 0
            this.ctr_level.selectedIndex = 1
            this.ctr_power.selectedIndex = 1
        end

        this.slider.value = (selectExp / need) * 100
        this.txt_sliderNum.text = selectExp .. "/" .. need
    end
end

function UIDebrisLevelUp:OnEnable(  )
    UIDebrisLevelUp.AddEvent()
    m_selected_list = {}
    UIDebrisLevelUp.Refresh()
end

function UIDebrisLevelUp.Refresh()
    this.ctr_levelUp.selectedIndex = 0
    m_selected_list = {}
    this.txt_name.text = m_chip_info.name

    this.txt_skilldes.text = m_chip_info.GetMainSkillDes()

    this.txt_level1.text = m_chip_info.level
    this.txt_power1.text = getNumString(m_chip_info.addPower)
    this.ctr_level.selectedIndex = 1
    this.ctr_power.selectedIndex = 1

    local item = CtrlManager.GetCtrl(PanelNames.Item);
    if item ~= nil then
        StrangeFragmentManager.SetItemData(this.inlayItem, m_chip_info, true)
        -- item.initData(this.inlayItem, m_chip_info, 1,true,nil,m_chip_info.partnerId)
        this.inlayItem.onClick:Clear()
    end

    local need = this.GetUpgradeNeedExp(m_chip_info)
    if need == 0 then
        this.btn_levelup.grayed = true
        this.slider.value = 100
        this.txt_sliderNum.text = m_chip_info.exp
    else
        this.slider.value = (m_chip_info.exp / need) * 100
        this.txt_sliderNum.text = m_chip_info.exp .. "/" .. need
    end

    m_cur_list = this.GetStuffList()--StrangeFragmentManager.GetOwnFragmentList()

    if #m_cur_list == 0 then
        this.ctr_nothing.selectedIndex = 1
    else
        this.ctr_nothing.selectedIndex = 0
        this.scroll_list.itemRenderer = this.SetData

        this.scroll_list:SetVirtual()
        this.scroll_list.numItems = #m_cur_list
    end
end

function UIDebrisLevelUp:OnClick_close()
    closeUI(PanelResNames.UIDebrisLevelUp)
end

function UIDebrisLevelUp:OnClick_levelup()
    local isPop = nil
    local need = this.GetUpgradeNeedExp(m_chip_info)
    if need == 0 then
        UISysTips.AddMsg(getLanguage("DebrisText24"))
        return
    else
        if table.getn(m_selected_list) == 0 then
            UISysTips.AddMsg(getLanguage("DebrisText25"))
            return
        end
    end

    local info = fragMgr.GetPanelInfo()
    local list = {}
    for k,v in pairs(m_selected_list) do
        if v.itemType == 64 and v.quality >=8 then
            isPop = true
        end
        table.insert(list, {itemid = tonumber(v.itemId), modelid = v.itemModelId, num = v.Num})
    end

    if #list > 0 then
        if isPop then
            local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop)
            pop.Init("108",function(b)
                if b then
                    weaponHandler.ReqLevelUpDebris(m_chip_info.partnerId, m_chip_info.itemId, 1, list)
                end
            end)
        else
            weaponHandler.ReqLevelUpDebris(m_chip_info.partnerId, m_chip_info.itemId, 1, list)
        end
    end
end

function UIDebrisLevelUp:OnClick_quickChoose()
    if #m_cur_list == 0 then
        return
    end
    m_selected_list = {}
    local need = this.GetUpgradeNeedExp(m_chip_info)
    if need == 0 then
        UISysTips.AddMsg(getLanguage("DebrisText24"))
        return
    end

    local expnum = m_chip_info.exp
    local sk_config = nil
    for k,v in pairs(m_cur_list) do
        if v.itemId ~= m_chip_info.itemId then
            if v.lock ~= 1 then
                if v.itemType == EnumConst.ItemTypeEnum.Fragment then
                    sk_config = dataTable.getDataTableByStringId("t_debrismajorskill",v.f_SkillId + v.level)
                    if sk_config then
                        expnum = expnum + sk_config.f_Exp
                    else
                        expnum = expnum + 0
                    end
                else
                    local count = math.ceil((need - expnum) / v.itemFunction[2])
                    if count > v.num then
                        v.Num = v.num
                    else
                        v.Num = count
                    end
                    expnum = expnum + v.itemFunction[2] * v.Num
                end

                m_selected_list[v.itemId] = v
                if expnum >= need then
                    break
                end
            end
        end
    end
    UIDebrisLevelUp:OnSelectExpChanged(expnum)

    this.scroll_list.numItems = #m_cur_list
end

function UIDebrisLevelUp:OnDisable()
    UIDebrisLevelUp.RemoveEvent()
end

function this.GetUpgradeNeedExp(chip)
    local key = tonumber(chip.f_SkillId) + chip.level
    local cur_skill = dataTable.getDataTableByStringId("t_debrismajorskill",key)
    local next_skill = dataTable.getDataTableByStringId("t_debrismajorskill",key + 1)
    if next_skill then
        return next_skill.f_TotalExp
    end

    return 0
end

function this.GetStuffList()
    local list = StrangeFragmentManager.GetOwnFragmentList()


    table.sort(list, sort_func)
    local it1 = ItemManager.getItemIdByModelId(200026)
    local it2 = ItemManager.getItemIdByModelId(200027)

    if it2 then
        table.insert(list, 1, clone(logicMgr.ItemManager.getItemData(it2)))
    end
    if it1 then
        table.insert(list, 1, clone(logicMgr.ItemManager.getItemData(it1)))
    end
    table.removeByValue(list, m_chip_info)
    return list
end

return UIDebrisLevelUp